package summer.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution144 {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        if (root != null) stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.removeLast();
            if (node != null) {
                if (node.right != null) stack.add(node.right);
                if (node.left != null) stack.add(node.left);
                stack.add(node);
                stack.add(null);
            } else {
                node = stack.removeLast();
                res.add(node.val);
            }
        }
        return res;
    }
}
